/**
 * 股票预测系统前端JavaScript
 * 负责与Tauri后端通信，处理股票预测相关的UI交互
 */

// 导入Tauri API
 

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initDatePickers();
    setupEventListeners();
    initCharts();
});

/**
 * 初始化日期选择器
 */
function initDatePickers() {
    // 设置默认日期范围：当前日期和一年前
    const today = new Date();
    const lastYear = new Date();
    lastYear.setFullYear(today.getFullYear() - 1);
    
    // 格式化日期为YYYY-MM-DD
    const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };
    
    // 设置开始日期和结束日期
    const startDateInput = document.getElementById('startDate');
    const endDateInput = document.getElementById('endDate');
    
    if (startDateInput && endDateInput) {
        startDateInput.value = formatDate(lastYear);
        endDateInput.value = formatDate(today);
        
        // 设置最大日期为今天
        startDateInput.max = formatDate(today);
        endDateInput.max = formatDate(today);
    }
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    // 为所有股票预测按钮添加事件监听
    const predictionButtons = document.querySelectorAll('[data-prediction-action]');
    predictionButtons.forEach(button => {
        button.addEventListener('click', (e) => {
            const action = e.target.getAttribute('data-prediction-action');
            if (action) {
                handlePredictionAction(action);
            }
        });
    });
    
    // 股票代码输入框自动完成
    const stockCodeInput = document.getElementById('stockCode');
    if (stockCodeInput) {
        stockCodeInput.addEventListener('input', debounce(async (e) => {
            if (e.target.value.length >= 2) {
                try {
                    const suggestions = await searchStockCodes(e.target.value);
                    updateStockSuggestions(suggestions);
                } catch (error) {
                    console.error('获取股票代码建议失败:', error);
                }
            }
        }, 300));
    }
    
    // 模型类型选择变化时更新UI
    const modelTypeSelect = document.getElementById('modelType');
    if (modelTypeSelect) {
        modelTypeSelect.addEventListener('change', (e) => {
            updateUIForModelType(e.target.value);
        });
    }
}

/**
 * 处理预测相关操作
 * @param {string} action - 操作类型
 */
async function handlePredictionAction(action) {
    try {
        // 显示加载状态
        showLoading(true);
        
        // 获取用户输入
        const params = getPredictionParams();
        
        // 调用后端API
        const result = await invoke('handle_stock_prediction', { 
            request: {
                action,
                params
            }
        });
        
        // 处理结果
        handlePredictionResult(result, action);
        
        // 显示成功消息
        showToast('操作成功完成', 'success');
    } catch (error) {
        console.error(`执行${action}操作失败:`, error);
        showToast(`操作失败: ${error.message || '未知错误'}`, 'error');
    } finally {
        // 隐藏加载状态
        showLoading(false);
    }
}

/**
 * 获取预测参数
 * @returns {Object} 预测参数对象
 */
function getPredictionParams() {
    const stockCode = document.getElementById('stockCode')?.value || '';
    const startDate = document.getElementById('startDate')?.value || '';
    const endDate = document.getElementById('endDate')?.value || '';
    const modelType = document.getElementById('modelType')?.value || 'predictor';
    
    return {
        stock_code: stockCode,
        start_date: startDate,
        end_date: endDate,
        model_type: modelType,
        // 添加其他可能需要的参数
        params: {
            time_steps: 60,
            test_size: 0.2,
            epochs: 50
        }
    };
}

/**
 * 处理预测结果
 * @param {Object} result - 预测结果
 * @param {string} action - 操作类型
 */
function handlePredictionResult(result, action) {
    // 更新结果显示区域
    updateResultDisplay(result);
    
    // 根据操作类型和结果更新图表
    updateCharts(result, action);
    
    // 记录操作日志
    logOperation(action, result);
}

/**
 * 更新结果显示区域
 * @param {Object} result - 预测结果
 */
function updateResultDisplay(result) {
    const resultElement = document.getElementById('prediction-result');
    if (!resultElement) return;
    
    // 格式化JSON显示
    let formattedResult = '';
    
    if (typeof result === 'object') {
        if (result.status === 'success') {
            // 成功结果的格式化显示
            formattedResult = formatSuccessResult(result);
        } else {
            // 错误结果的格式化显示
            formattedResult = `❌ 错误: ${result.message || '未知错误'}\n`;
            if (result.details) {
                formattedResult += `详情: ${JSON.stringify(result.details, null, 2)}`;
            }
        }
    } else {
        formattedResult = String(result);
    }
    
    resultElement.textContent = formattedResult;
}

/**
 * 格式化成功结果
 * @param {Object} result - 成功的预测结果
 * @returns {string} 格式化后的结果文本
 */
function formatSuccessResult(result) {
    let formatted = `✅ 状态: ${result.status}\n\n`;
    
    if (result.stock_code) {
        formatted += `📊 股票代码: ${result.stock_code}\n`;
    }
    
    if (result.trading_signal) {
        formatted += `\n📈 交易信号: ${result.trading_signal.signal}\n`;
        formatted += `信号强度: ${result.trading_signal.strength}%\n`;
    }
    
    if (result.predictions) {
        formatted += `\n🔮 预测结果:\n`;
        if (Array.isArray(result.predictions)) {
            result.predictions.forEach((pred, i) => {
                formatted += `  ${i+1}. ${typeof pred === 'number' ? pred.toFixed(2) : pred}\n`;
            });
        } else {
            formatted += `  ${result.predictions}\n`;
        }
    }
    
    if (result.evaluation) {
        formatted += `\n📝 评估指标:\n`;
        for (const [key, value] of Object.entries(result.evaluation)) {
            if (typeof value === 'object') {
                formatted += `  ${key}:\n`;
                for (const [subKey, subValue] of Object.entries(value)) {
                    formatted += `    ${subKey}: ${typeof subValue === 'number' ? subValue.toFixed(4) : subValue}\n`;
                }
            } else {
                formatted += `  ${key}: ${typeof value === 'number' ? value.toFixed(4) : value}\n`;
            }
        }
    }
    
    if (result.summary) {
        formatted += `\n📋 摘要:\n`;
        result.summary.forEach((item, i) => {
            formatted += `  ${i+1}. ${item}\n`;
        });
    }
    
    return formatted;
}

/**
 * 更新图表
 * @param {Object} result - 预测结果
 * @param {string} action - 操作类型
 */
function updateCharts(result, action) {
    const chartContainer = document.getElementById('chart-container');
    if (!chartContainer) return;
    
    // 清空现有图表
    chartContainer.innerHTML = '';
    
    // 根据操作类型和结果创建不同的图表
    if (action.includes('predict') && result.predictions) {
        createPredictionChart(chartContainer, result);
    } else if (action.includes('analyze') && result.analysis) {
        createAnalysisChart(chartContainer, result);
    } else if (action.includes('train') && result.evaluation) {
        createTrainingChart(chartContainer, result);
    } else if (action.includes('select') && result.selected_stocks) {
        createStockSelectionChart(chartContainer, result);
    } else {
        // 默认显示结果摘要图表
        createSummaryChart(chartContainer, result);
    }
}

/**
 * 创建预测图表
 * @param {HTMLElement} container - 图表容器
 * @param {Object} result - 预测结果
 */
function createPredictionChart(container, result) {
    // 这里将使用Chart.js创建预测图表
    // 在实际实现中，需要引入Chart.js库
    
    // 创建canvas元素
    const canvas = document.createElement('canvas');
    container.appendChild(canvas);
    
    // 这里是Chart.js的示例代码，需要根据实际情况调整
    /*
    new Chart(canvas, {
        type: 'line',
        data: {
            labels: result.dates || Array(result.predictions.length).fill().map((_, i) => `Day ${i+1}`),
            datasets: [
                {
                    label: '历史价格',
                    data: result.recent_prices || [],
                    borderColor: 'rgba(75, 192, 192, 1)',
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderWidth: 2,
                    pointRadius: 3
                },
                {
                    label: '预测价格',
                    data: result.predictions || [],
                    borderColor: 'rgba(153, 102, 255, 1)',
                    backgroundColor: 'rgba(153, 102, 255, 0.2)',
                    borderWidth: 2,
                    pointRadius: 3,
                    borderDash: [5, 5]
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: '日期'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: '价格'
                    }
                }
            }
        }
    });
    */
    
    // 临时显示图表信息
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.display = 'flex';
    canvas.style.alignItems = 'center';
    canvas.style.justifyContent = 'center';
    canvas.style.backgroundColor = '#f9fafb';
    canvas.style.border = '1px dashed #d1d5db';
    canvas.style.borderRadius = '0.5rem';
    canvas.textContent = '图表将在此显示 (需要引入Chart.js)';
}

/**
 * 创建分析图表
 * @param {HTMLElement} container - 图表容器
 * @param {Object} result - 分析结果
 */
function createAnalysisChart(container, result) {
    // 分析图表实现
    const infoDiv = document.createElement('div');
    infoDiv.className = 'p-4 bg-blue-50 rounded-lg';
    infoDiv.innerHTML = `
        <h3 class="text-lg font-semibold text-blue-800 mb-2">分析结果</h3>
        <p class="text-blue-600">图表将根据分析结果显示相关指标和趋势</p>
    `;
    container.appendChild(infoDiv);
}

/**
 * 创建训练图表
 * @param {HTMLElement} container - 图表容器
 * @param {Object} result - 训练结果
 */
function createTrainingChart(container, result) {
    // 训练图表实现
    const infoDiv = document.createElement('div');
    infoDiv.className = 'p-4 bg-green-50 rounded-lg';
    infoDiv.innerHTML = `
        <h3 class="text-lg font-semibold text-green-800 mb-2">训练结果</h3>
        <p class="text-green-600">图表将显示训练过程中的损失和准确率变化</p>
    `;
    container.appendChild(infoDiv);
}

/**
 * 创建选股图表
 * @param {HTMLElement} container - 图表容器
 * @param {Object} result - 选股结果
 */
function createStockSelectionChart(container, result) {
    // 选股图表实现
    const infoDiv = document.createElement('div');
    infoDiv.className = 'p-4 bg-purple-50 rounded-lg';
    infoDiv.innerHTML = `
        <h3 class="text-lg font-semibold text-purple-800 mb-2">选股结果</h3>
        <p class="text-purple-600">图表将显示选中的股票及其评分</p>
    `;
    container.appendChild(infoDiv);
}

/**
 * 创建摘要图表
 * @param {HTMLElement} container - 图表容器
 * @param {Object} result - 结果数据
 */
function createSummaryChart(container, result) {
    // 摘要图表实现
    const infoDiv = document.createElement('div');
    infoDiv.className = 'p-4 bg-gray-50 rounded-lg';
    infoDiv.innerHTML = `
        <h3 class="text-lg font-semibold text-gray-800 mb-2">结果摘要</h3>
        <p class="text-gray-600">操作完成，请查看左侧文本结果详情</p>
    `;
    container.appendChild(infoDiv);
}

/**
 * 初始化图表
 */
function initCharts() {
    const chartContainer = document.getElementById('chart-container');
    if (chartContainer) {
        const welcomeDiv = document.createElement('div');
        welcomeDiv.className = 'flex items-center justify-center h-full';
        welcomeDiv.innerHTML = `
            <div class="text-center p-6">
                <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                          d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z">
                    </path>
                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900">暂无数据</h3>
                <p class="mt-1 text-sm text-gray-500">请选择一个操作来生成图表</p>
            </div>
        `;
        chartContainer.appendChild(welcomeDiv);
    }
}

/**
 * 搜索股票代码
 * @param {string} query - 搜索关键词
 * @returns {Promise<Array>} 股票代码建议列表
 */
async function searchStockCodes(query) {
    try {
        // 调用后端API获取股票代码建议
        const result = await invoke('search_stock_codes', { query });
        return result || [];
    } catch (error) {
        console.error('搜索股票代码失败:', error);
        return [];
    }
}

/**
 * 更新股票代码建议
 * @param {Array} suggestions - 建议列表
 */
function updateStockSuggestions(suggestions) {
    // 实现股票代码自动完成功能
    const stockCodeInput = document.getElementById('stockCode');
    const suggestionsContainer = document.getElementById('stock-suggestions');
    
    if (!suggestionsContainer) {
        // 创建建议容器
        const container = document.createElement('div');
        container.id = 'stock-suggestions';
        container.className = 'absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md py-1 text-sm';
        stockCodeInput.parentNode.appendChild(container);
    }
    
    const container = document.getElementById('stock-suggestions');
    container.innerHTML = '';
    
    if (suggestions.length > 0) {
        suggestions.forEach(stock => {
            const item = document.createElement('div');
            item.className = 'px-4 py-2 hover:bg-gray-100 cursor-pointer';
            item.textContent = `${stock.code} - ${stock.name}`;
            item.addEventListener('click', () => {
                stockCodeInput.value = stock.code;
                container.innerHTML = '';
            });
            container.appendChild(item);
        });
    } else {
        container.innerHTML = '<div class="px-4 py-2 text-gray-500">无匹配结果</div>';
    }
}

/**
 * 根据模型类型更新UI
 * @param {string} modelType - 模型类型
 */
function updateUIForModelType(modelType) {
    // 根据不同的模型类型更新UI元素
    const additionalParamsContainer = document.getElementById('additional-params');
    if (!additionalParamsContainer) return;
    
    switch (modelType) {
        case 'predictor':
            additionalParamsContainer.innerHTML = `
                <div class="form-group">
                    <label class="form-label">时间步长</label>
                    <input type="number" id="timeSteps" class="form-input" value="60" min="10" max="120">
                </div>
                <div class="form-group">
                    <label class="form-label">训练轮数</label>
                    <input type="number" id="epochs" class="form-input" value="50" min="10" max="200">
                </div>
            `;
            break;
        case 'closing_selector':
            additionalParamsContainer.innerHTML = `
                <div class="form-group">
                    <label class="form-label">选股数量</label>
                    <input type="number" id="selectCount" class="form-input" value="10" min="1" max="100">
                </div>
                <div class="form-group">
                    <label class="form-label">选股策略</label>
                    <select id="selectStrategy" class="form-select">
                        <option value="momentum">动量策略</option>
                        <option value="value">价值策略</option>
                        <option value="mixed">混合策略</option>
                    </select>
                </div>
            `;
            break;
        case 'enhanced_closing_selector':
            additionalParamsContainer.innerHTML = `
                <div class="form-group">
                    <label class="form-label">选股数量</label>
                    <input type="number" id="selectCount" class="form-input" value="10" min="1" max="100">
                </div>
                <div class="form-group">
                    <label class="form-label">风险等级</label>
                    <select id="riskLevel" class="form-select">
                        <option value="low">低风险</option>
                        <option value="medium">中等风险</option>
                        <option value="high">高风险</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">包含情绪分析</label>
                    <input type="checkbox" id="includeSentiment" class="form-checkbox" checked>
                </div>
            `;
            break;
        default:
            additionalParamsContainer.innerHTML = '';
    }
}

/**
 * 显示/隐藏加载状态
 * @param {boolean} isLoading - 是否加载中
 */
function showLoading(isLoading) {
    const loadingElement = document.getElementById('loading-indicator');
    if (loadingElement) {
        loadingElement.style.display = isLoading ? 'flex' : 'none';
    }
}

/**
 * 显示通知提示
 * @param {string} message - 提示消息
 * @param {string} type - 提示类型 (success, error, warning, info)
 */
function showToast(message, type = 'info') {
    // 创建或获取toast容器
    let toastContainer = document.getElementById('toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'fixed bottom-4 right-4 z-50';
        document.body.appendChild(toastContainer);
    }
    
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = `toast toast-${type} mb-2`;
    toast.innerHTML = `
        <div class="flex items-center">
            <span class="mr-2">${getToastIcon(type)}</span>
            <span>${message}</span>
        </div>
    `;
    
    // 添加到容器
    toastContainer.appendChild(toast);
    
    // 动画效果
    setTimeout(() => {
        toast.classList.add('opacity-0');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}

/**
 * 获取toast图标
 * @param {string} type - 提示类型
 * @returns {string} 图标HTML
 */
function getToastIcon(type) {
    switch (type) {
        case 'success':
            return '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>';
        case 'error':
            return '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';
        case 'warning':
            return '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>';
        case 'info':
        default:
            return '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>';
    }
}

/**
 * 记录操作日志
 * @param {string} action - 操作类型
 * @param {Object} result - 操作结果
 */
function logOperation(action, result) {
    console.log(`[${new Date().toISOString()}] 执行操作: ${action}`, result);
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} wait - 等待时间(ms)
 * @returns {Function} 防抖处理后的函数
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * 调用股票预测后端API
 * @param {string} action - 操作类型
 * @param {Object} params - 参数
 * @returns {Promise<Object>} 操作结果
 */
async function callStockPredictionAPI(action, params = {}) {
    try {
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = 'flex';
        }
        
        // 调用Tauri API
        const result = await invoke('plugin:stock_prediction|' + action, params);
        
        // 更新结果显示
        const resultElement = document.getElementById('prediction-result');
        if (resultElement) {
            if (typeof result === 'object') {
                resultElement.textContent = JSON.stringify(result, null, 2);
            } else {
                resultElement.textContent = String(result);
            }
        }
        
        return result;
    } catch (error) {
        console.error(`调用股票预测API失败 (${action}):`, error);
        
        // 显示错误信息
        const resultElement = document.getElementById('prediction-result');
        if (resultElement) {
            resultElement.textContent = `错误: ${error.message || '未知错误'}`;
        }
        
        throw error;
    } finally {
        // 隐藏加载状态
        const loadingIndicator = document.getElementById('loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = 'none';
        }
    }
}